package com.xjgc.ws.mes.dao;

import com.xjgc.common.config.DbConn;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;

/**
 * ----成品入库 SAP回传操作--------
 * @author jjg-pc
 *实现单表的XML数据解析并组装成SQL语句执行
 */
@Component
public class ZxjS2Mcprk {

	@Autowired
	DbConn db;
	/**
	 * @param xml
	 * @return
	 * @throws SQLException 
	 */
	public String fhhc(String xml) throws SQLException{
		
		String rs = null;
		PreparedStatement updPst = null;
		
		//定义执行SQL脚本
		String updSql = "update zxj_m2s_cprk set mblnr = ?,message=?,sap_ops=? where aufnr=? and werks=? and posnr=?";  
		//创建数据库连接
		updPst = db.getConnetion().prepareStatement(updSql);
		int count=0;
		//解析xml文件
		Document doc = null;
//		System.out.println("************   xml== "+xml);
		try {
			doc = DocumentHelper.parseText(xml);
			Element root = doc.getRootElement();
			Iterator<?> it = root.elementIterator();
			
			while(it.hasNext()) {
				
				Element element = (Element) it.next();
				
				updPst.setString(1, element.elementText("MBLNR"));
				updPst.setString(2, element.elementText("MESSAGE"));
				updPst.setString(3, element.elementText("SAP_OPS"));
				updPst.setString(4, element.elementText("AUFNR"));
				updPst.setString(5, element.elementText("WERKS"));
				updPst.setString(6, element.elementText("POSNR"));
				
				int row = updPst.executeUpdate();
				if(row>0) {
					count++;
				}
			}

		} catch (DocumentException e1) {
			rs=e1.toString();//执行失败
			e1.printStackTrace();
		}
		
		if (count>0) {
			rs = "0";//执行成功
		}else {
			rs = "无更新数据！！";
		}
		
		//关闭连接
		updPst.close();
		db.closeCn();
		return rs;
	}
}
